package cn.shuangliang.contract.web.interceptor;

import org.springframework.stereotype.Service;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author oldliu
 * @since 1.0
 */
@Service("timeInterceptor")
public class TimeInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setAttribute("start", System.nanoTime());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        long end = System.nanoTime();
        long time = end - (Long) request.getAttribute("start");
        System.out.println(request.getServletPath() + "......" + handler + " 执行，花费 " + time + "纳秒");
    }
}
